/*
 *  author: lichuang
 *  2010-09-27
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include "array.h"

array_t* array_create(int size) {
  array_t *array = (array_t*)malloc(sizeof(array_t) + size * sizeof(int));
  assert(array != NULL);
  array->size = size;
  return array;
}

array_t* array_resize(array_t *array, int new_size) {
  assert(array != NULL);
  array_t *p = (array_t*)malloc(sizeof(array_t) + new_size * sizeof(int));
  assert(p != NULL);
  int size = new_size > array->size ? array->size : new_size;
  memcpy(p->data, array->data, size * sizeof(int));
  p->size = new_size;
  free(array);
  return p;
}

void array_destroy(array_t *array) {
  assert(array != NULL);
  free(array);
}

void array_init(array_t *array) {
  assert(array != NULL);
  time_t t = time(NULL);
  srand(t);
  int i, size, max;
  int *p = array->data;
  for (i = 0, size = array->size, max = size * 100; i < size; ++i) {
    p[i] = rand() % max;
  }
}

void array_print(const array_t *array, const char *msg) {
  int i, size;
  const int *p;
  if (msg != NULL) {
    printf("%s\n", msg);
  } else {
    printf("\n");
  }
  for (i = 0, size = array->size, p = array->data; i < size; ++i) {
    printf("%d ", p[i]);
  }
  printf("\n");
}

int  array_check_sorted(const array_t *array) {
  int tmp, i, size;
  const int *p = array->data;
  for (tmp = p[0], i = 1, size = array->size; i < size; ++i) {
    if (tmp > p[i]) {
      return 0;
    }
  }
  return 1;
}
